package com.linln.wxapi;

import java.util.ArrayList;
import java.util.List;

import com.linln.common.constant.StatusConst;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @author hct
 *
 */
@Api(value="区域信息管理")
@RestController
@RequestMapping("/wx/areainfo/{area}")
public class WxApiAreaController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AreaService areaService;
    @Autowired
    private MemberInfoService memberService;
    @Autowired
    private MemberAgentService agentService;

    /**
     * 获取区域信息
     * @param area 区域
     * @return
     */
     @ApiOperation(value = "获取区域信息",  notes = "获取区域信息")
     @ApiImplicitParams({
          @ApiImplicitParam(name = "arealist", value = "获取区域信息",paramType = "query", required = true, dataType = "int")
     })
     @RequestMapping(value = "/list",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo arealist(@PathVariable String area) {
        
         try {
         	// 创建匹配器，进行动态查询匹配
             ExampleMatcher matcher = ExampleMatcher.matching();
                     //.withMatcher("type_name", match -> match.contains())
              Area ad=new Area();

             // 获取数据列表
             Example<Area> example = Example.of(ad, matcher);
             Long a=System.currentTimeMillis();
             Sort sort = new Sort(Sort.Direction.ASC, "id");
             List<Area> list = areaService.getListByExample(example, sort);
             List<Area> listnew=TreeUtil.buildByRecursive(list);
             System.out.println("b==="+(System.currentTimeMillis()-a));
             return ResultVoUtil.success(listnew);

            // return ResultVoUtil.success(list);

         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
     
     
     
     /**
      * 获取区域信息
      * @param area 区域
      * @return
      */
      @ApiOperation(value = "获取区域信息",  notes = "获取区域信息")
      @ApiImplicitParams({
           @ApiImplicitParam(name = "queryAreaList", value = "根据条件返回区域信息",paramType = "query", required = true, dataType = "int")
      })
      @RequestMapping(value = "/queryAreaList",method={RequestMethod.POST,RequestMethod.GET})
      @ResponseBody
      public ResultVo queryAreaList(@PathVariable String area,String searchName) {
         
          try {
        	  if(searchName==null || searchName.equals("")) {
        		  return ResultVoUtil.success("没有搜索条件"); 
        	  }
              List<Area> list = areaService.getListBySearchName(searchName);
              if(list==null || list.size()==0) {
                  return ResultVoUtil.success("没有数据"); 
              }
              long a=System.currentTimeMillis();
              //过滤父
              list=TreeUtil.findParentren(list); 
              List<Long> listIds=TreeUtil.findParentrenIds(list);
              List<Area> parentlist = areaService.getParentByIds(listIds);
              List<Area> listnew=TreeUtil.findParentren(list,parentlist);
             // return ResultVoUtil.success(TreeUtil.buildByRecursive(list));                           
              System.out.println("b==="+(System.currentTimeMillis()-a));

              return ResultVoUtil.success(listnew);

          } catch (Exception e) {
              this.logger.error(e.getMessage(), e);
              return ResultVoUtil.error("接口异常"); 
          }
      }
     
     
     /**
      * 我代理的区域接口
      * @param area 区域
      * @return
      */
      @ApiOperation(value = "获取区域信息",  notes = "获取区域信息")
      @ApiImplicitParams({
           @ApiImplicitParam(name = "agentlist", value = "获取代理的区域信息",paramType = "query", required = true, dataType = "int")
      })
      @RequestMapping(value = "/agentlist",method={RequestMethod.POST,RequestMethod.GET})
      @ResponseBody
      public ResultVo agentarealist(@PathVariable String area,Long memberId) {
         
          try {
          	// 创建匹配器，进行动态查询匹配
             // MemberInfo memberInfo=memberService.getById(memberId);
              MemberAgent memberagentarea=new MemberAgent();
              MemberInfo member=new MemberInfo();
              member.setId(memberId);
              memberagentarea.setMember(member);
              memberagentarea.setStatus(StatusConst.OK);
              ExampleMatcher matcher = ExampleMatcher.matching();
              Example<MemberAgent> example = Example.of(memberagentarea, matcher);
              List<MemberAgent>arealist=agentService.getList(example);
              List<String> areas=new ArrayList<String>();
              for (MemberAgent memberAgent :arealist
              ) {
                  if(memberAgent==null) continue;
                  areas.add(memberAgent.getArea());
              }
              List<Area> list = areaService.findByCodeIn(areas);
              return ResultVoUtil.success(list);
          } catch (Exception e) {
              this.logger.error(e.getMessage(), e);
              return ResultVoUtil.error("接口异常"); 
          }
      }
      
      /**
       * 获取城市信息
       * @param area 区域
       * @return
       */
       @ApiOperation(value = "根据市获取区县信息",  notes = "获取区域信息")
       @ApiImplicitParams({
            @ApiImplicitParam(name = "getCityList", value = "获取城市列表",paramType = "query", required = true)
       })
       @RequestMapping(value = "/getCityList",method={RequestMethod.POST,RequestMethod.GET})
       @ResponseBody
       public ResultVo getCityList(@PathVariable String area) {
          
           try {
               List<Area> list =areaService.getCityList();
               return ResultVoUtil.success(list);
           } catch (Exception e) {
               this.logger.error(e.getMessage(), e);
               return ResultVoUtil.error("接口异常"); 
           }
       }
      
      /**
       * 获取区域信息
       * @param area 区域
       * @return
       */
       @ApiOperation(value = "根据市获取区县信息",  notes = "获取区域信息")
       @ApiImplicitParams({
            @ApiImplicitParam(name = "getAreaByCityName", value = "根据市获取区县信息",paramType = "query", required = true)
       })
       @RequestMapping(value = "/getAreaByCityName",method={RequestMethod.POST,RequestMethod.GET})
       @ResponseBody
       public ResultVo agentarealist(@PathVariable String area,String cityName) {
          
           try {
               Area areanew = areaService.findByName(cityName);
               List<Area> list =new ArrayList<Area>();
               if(areanew!=null) {
            	   list=areaService.getListByPid(areanew.getId());
               }
               return ResultVoUtil.success(list);
           } catch (Exception e) {
               this.logger.error(e.getMessage(), e);
               return ResultVoUtil.error("接口异常"); 
           }
       }
    
}
